// 将平铺数据转换为树形结构  根据 id 和 parentId 的关系
// 定义节点的接口
export interface DepartmentNode {
  id: number
  name: string
  parentId: number
  children: DepartmentNode[]
}

type FlatDataItem = Omit<DepartmentNode, 'children'>

export function useDepartmentTree(flatData: FlatDataItem[]): DepartmentNode[] {
  const treeData = ref<DepartmentNode[]>([])

  const buildTree = (data: FlatDataItem[]): DepartmentNode[] => {
    try {
      const map = new Map<number, DepartmentNode>()
      data.forEach((item) => {
        map.set(item.id, { ...item, children: [] })
      })

      const tree: DepartmentNode[] = []
      data.forEach((item) => {
        if (item.parentId === 0) {
          tree.push(map.get(item.id)!)
        } else {
          const parent = map.get(item.parentId)
          if (parent) {
            parent.children.push(map.get(item.id)!)
          }
        }
      })

      return tree
    } catch (error) {
      console.error('构建树结构时出错:', error)
      return []
    }
  }

  try {
    treeData.value = buildTree(flatData)
  } catch (error) {
    console.error('初始化树数据时出错:', error)
  }

  return treeData.value
}
